<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px query-form"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
    >
      <el-form-item label="客户姓名" prop="username">
        <el-input
          v-model="queryParams.username"
          placeholder=""
          clearable
          @keyup.enter="handleQuery"
          style="width: 100px;"
        />
      </el-form-item>
      <!-- <el-form-item label="贷款额度" prop="quota">
        <el-select
          v-model="queryParams.quota"
          placeholder="请选择贷款额度"
          clearable
        >
          <el-option
            v-for="dict in getIntDictOptions(DICT_TYPE.QUOTA)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item> -->
      <!-- <el-form-item label="跟进人" prop="followUpName">
        <el-input
          v-model="queryParams.followUpName"
          placeholder="请输入跟进人"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item> -->
      <el-form-item label="跟进状态" prop="followUpStatus">
        <el-select
          v-model="queryParams.followUpStatus"
          placeholder=""
          clearable
          style="width: 90px;"
        >
          <el-option
            v-for="dict in getIntDictOptions(DICT_TYPE.FOLLOWUPSTATUS)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="来源" prop="source">
        <el-select
          v-model="queryParams.source"
          placeholder=""
          clearable
          style="width: 120px;"
        >
          <el-option
            v-for="dict in getIntDictOptions(DICT_TYPE.CRM_CUSTOMER_SOURCE)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <!-- <el-form-item label="客户类型" prop="customerType">
        <el-select
          v-model="queryParams.customerType"
          placeholder="请选择客户类型"
          clearable
        >
          <el-option
            v-for="dict in getIntDictOptions(DICT_TYPE.CUSTOMER_TYPE)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item> -->
      <el-form-item label="客户星级" prop="starRating">
        <el-select
          v-model="queryParams.starRating"
          placeholder=""
          clearable
          style="width: 50px;"
        >
          <el-option
            v-for="dict in getIntDictOptions(DICT_TYPE.CUSTOMERSTARRATING)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="房产" prop="realestate">
        <el-select
          v-model="queryParams.realestate"
          placeholder=""
          clearable
          style="width: 70px;"
        >
          <el-option
            v-for="dict in getIntDictOptions(DICT_TYPE.REALESTATE)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="公积金" prop="housingProvidentFund">
        <el-select
          v-model="queryParams.housingProvidentFund"
          placeholder=""
          clearable
          style="width: 80px;"
        >
          <el-option
            v-for="dict in getIntDictOptions(DICT_TYPE.HOUSINGPROVIDENTFUND)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="社保" prop="socialinsurance">
        <el-select
          v-model="queryParams.socialinsurance"
          placeholder=""
          clearable
          style="width: 70px;"
        >
          <el-option
            v-for="dict in getIntDictOptions(DICT_TYPE.SOCIALINSURANCE)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="跟进时间" prop="followTime">
        <el-date-picker
          v-model="queryParams.followTime"
          value-format="YYYY-MM-DD HH:mm:ss"
          type="daterange"
          clear-icon=""
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
          style="width: 140px;"
        />
      </el-form-item>
      <el-form-item label="申请时间" prop="createTime">
        <el-date-picker
          v-model="queryParams.createTime"
          value-format="YYYY-MM-DD HH:mm:ss"
          type="daterange"
          clear-icon=""
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
          style="width: 140px;"
        />
      </el-form-item>
      <el-form-item label="手机号码" prop="mobile">
        <el-input
          v-model="queryParams.mobile"
          placeholder=""
          type="tel"
          clearable
          @keyup.enter="handleQuery"
          style="width: 100px;"
        />
      </el-form-item>
      <el-form-item label="业务经理">
        <el-select
          v-loading="loading"
          v-model="queryParams.followUp"
          @change="() => handleQuery()"
          placeholder=""
          clearable
          style="width: 120px;"
        >
          <el-option
            v-for="item in followUpList"
            :key="item.id"
            :value="item.id"
            :label="item.username"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery"><Icon icon="ep:search" class="mr-5px" /> 搜索</el-button>
        <el-button @click="resetQuery"><Icon icon="ep:refresh" class="mr-5px" /> 重置</el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table
      row-key="id"
      v-loading="loading"
      border
      :data="list"
      :stripe="true"
      :show-overflow-tooltip="true"
      :height="540"
      :row-style="({ row }) => (0 === row.status ? { color: 'red' } : {})"
      @row-click="handleRowClick"
      @selection-change="handleRowCheckboxChange"
      @sort-change="handleSortChange"
    >
      <el-table-column :resizable="false" type="selection" align="center" width="40px" fixed="left" />
      <el-table-column :resizable="false" label="姓名" align="center" prop="username"  />
      <el-table-column :resizable="false" label="年龄" align="center" prop="age"  />
      <el-table-column :resizable="false" label="性别" align="center" prop="sex" >
        <template #default="scope">
          {{ getDictLabel(DICT_TYPE.SYSTEM_USER_SEX, scope.row.sex) }}
        </template>
      </el-table-column>
      <el-table-column :resizable="false" label="额度" align="center" prop="quota" />
      <el-table-column :resizable="false" label="跟进人" align="center" prop="followUpName"  />
      <el-table-column :resizable="false" label="跟进状态" align="center" prop="followUpStatus" >
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.FOLLOWUPSTATUS" :value="scope.row.followUpStatus" />
        </template>
      </el-table-column>
      <el-table-column :resizable="false" label="客户星级" align="center" prop="starRating" >
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.CUSTOMERSTARRATING" :value="scope.row.starRating" />
        </template>
      </el-table-column>
      <el-table-column :resizable="false" label="客户属性" align="center" >
        <template #default="{ row }">
          <template v-if="!CustomerProps(row).length">无</template>
          {{ CustomerProps(row) }}
          <!-- <div class="tag-group">
          </div> -->
        </template>
      </el-table-column>
      <el-table-column :resizable="false" label="客户条件备注" align="center" prop="remark" width="145px" />
      <el-table-column :resizable="false" label="跟进情况备注" align="center" prop="followRemark" width="145px" />
      <el-table-column :resizable="false" label="跟进次数" align="center" prop="followUpFrequency" />
      <el-table-column :resizable="false" label="来源" align="center" prop="source" width="145px">
        <template #default="scope">
          {{ getDictLabel(DICT_TYPE.CRM_CUSTOMER_SOURCE, scope.row.source) }}
        </template>
      </el-table-column>
      <el-table-column
        :resizable="false"
        label="最后跟进时间"
        align="center"
        prop="followTime"
        :formatter="dateFormatter"
        sortable
        width="145px"
      >
        <template #header>
          最后跟进时间
          <span class="caret-wrapper custom">
            <i :style="{ 'border-bottom-color': 1 === queryParams.sortFollowOrder ? 'var(--el-color-primary)' : 'var(--el-text-color-placeholder)'  }" class="sort-caret ascending"></i>
            <i :style="{ 'border-top-color': 0 === queryParams.sortFollowOrder ? 'var(--el-color-primary)' : 'var(--el-text-color-placeholder)'  }" class="sort-caret descending"></i>
          </span>
        </template>
      </el-table-column>
      <el-table-column
        :resizable="false"
        label="申请时间"
        align="center"
        prop="createTime"
        :formatter="dateFormatter"
        sortable
        width="145px"
      >
        <template #header>
          申请时间
          <span class="caret-wrapper custom">
            <i :style="{ 'border-bottom-color': 1 === queryParams.sortcreateTime ? 'var(--el-color-primary)' : 'var(--el-text-color-placeholder)'  }" class="sort-caret ascending"></i>
            <i :style="{ 'border-top-color': 0 === queryParams.sortcreateTime ? 'var(--el-color-primary)' : 'var(--el-text-color-placeholder)'  }" class="sort-caret descending"></i>
          </span>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        :resizable="false"
        align="center"
        width="145px"
        fixed="right">
        <template #default="scope">
          <!-- @click.stop="openForm('update', scope.row.id)" -->
          <el-button
            link
            type="primary"
            @click.stop="() => handleRowClick(scope.row)"
            v-hasPermi="['system:customer:update']"
          >
            详情
          </el-button>
          <el-button
            link
            type="danger"
            @click.stop="handleDelete(scope.row.id)"
            v-hasPermi="['system:customer:delete']"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination
      :total="total"
      :page-sizes="[50, 100]"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>

  <!-- 表单弹窗：添加/修改 -->
  <customerForm ref="formRef" @success="getList" />

  <!-- 客户分配 -->
  <AssignDialog ref="assignDialogRef" @submit="handleAssign" />

  <!-- 跟进表单 -->
  <FollowUpDialog
    ref="followUpDialogRef"
    :get-info-method="customerApi.getcustomer"
    :info-list="list"
    :get-info-list-method="getList"
    :save="handleFollowUpSave"
    :get-history-method="info => customerApi.getRemarkHistory({ customerId: info.id })"
    :get-loan-page-method="info => loanApi.getloanPage({ pageNo: 1, pageSize: 30, customerId: info.id})"
    :show-assign-dialog="showAssignDialog"
  />
</template>

<script setup lang="ts">
import { getIntDictOptions, DICT_TYPE, getDictLabel } from '@/utils/dict'
import { dateFormatter } from '@/utils/formatTime'
import { customerApi, customer } from '@/api/system/customer'
import customerForm from '../customer/customerForm.vue'
import AssignDialog from '../customer/AssignDialog.vue'
import FollowUpDialog from '../customer/FollowUpDialog.vue'
import { omit } from 'lodash-es'
import { useUserStore } from '@/store/modules/user'
import { loanApi } from '@/api/system/loan'

const userStore = useUserStore();

/** 客户 列表 */
defineOptions({ name: 'CustomerDetail' })
const router = useRouter();
const route = useRoute();
if (!Object.keys(route.query).length) {
  router.back();
}
const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const loading = ref(true) // 列表的加载中
const list = ref<customer[]>([]) // 列表的数据
provide('infoList', list);
const total = ref(0); // 列表的总页数
['followUpStatus','source','starRating','realestate','housingProvidentFund','socialinsurance'].forEach(prop => {
  route.query[prop] = route.query[prop] && Number(route.query[prop]);
})
const queryParams = reactive(Object.assign(
  {
    pageNo: 1,
    pageSize: 50,
    username: undefined,
    sex: undefined,
    age: undefined,
    quota: undefined,
    mobile: undefined,
    createTime: [],
    followUpInitial: undefined,
    followUp: undefined,
    followUpName: undefined,
    followUpStatus: undefined,
    remark: undefined,
    followUpFrequency: undefined,
    source: undefined,
    starRating: undefined,
    realestate: undefined,
    housingProvidentFund: undefined,
    socialinsurance: undefined,
    customerType: undefined,
    followTime: [],
    /** 正序=1 倒序=0 */
    sortFollowOrder: undefined,
    /** 正序=1 倒序=0 */
    sortcreateTime: undefined,
    status: undefined,
  },
  omit(route.query, ['pageNo', 'pageSize']),
));
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中
const currentRow = ref({}) // 选中行


/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await customerApi.getCountUserDetailInfo(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}
provide('getList', getList);

function CustomerProps(row) {
  return [
    {
      type: DICT_TYPE.REALESTATE,
      prop: 'realestate',
      validator: x => [0,1].includes(x),
    },
    {
      type: DICT_TYPE.HOUSINGPROVIDENTFUND,
      prop: 'housingProvidentFund',
      validator: x => [0].includes(x),
    },
    {
      type: DICT_TYPE.SOCIALINSURANCE,
      prop: 'socialinsurance',
      validator: x => [0].includes(x),
    }
  ]
  .filter(item => item.validator(row[item.prop]))
  .map(item => getDictLabel(item.type, row[item.prop]))
  .join('/');
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

function handleSortChange({ column, prop, order }) {
  function Value() {
    // 下标为 -1 则值为 undefined，正好对应不传
    const i = ['descending', 'ascending'].indexOf(order);
    return [0, 1][i];
  }

  function Prop() {
    return {
      followTime: 'sortFollowOrder',
      createTime: 'sortcreateTime',
    }[prop];
  }

  queryParams[Prop()] = Value();
  getList();
}

function handleFollowUpSave(info, infoInitial) {
  // 若某些字段值没变，则不传那些字段值
  // 目前有跟进状态、跟进备注
  const needCheckProps = ['followUpStatus', 'followRemark'];
  const isNoModified = prop => info.value[prop] == infoInitial.value[prop];
  const omitProps = needCheckProps.filter(isNoModified);
  return customerApi.updatecustomer(omit(info.value, omitProps));
}

const followUpList = ref([]);
function getFollowUpList() {
  return customerApi.getFollowUpList()
  .then(data => {
    followUpList.value = data;
    queryParams.followUp = userStore.getUser.id;
  });
}

function handleMovingIntoImportant(ids) {
  loading.value = true;
  return customerApi.movingIntoImportant({
    ids
  })
  .then(() => {
    ElMessage.success('已标为重要客户');
    return getList();
  })
  .finally(() => {
    loading.value = false;
  });
}

function handleMyCustomer(ids) {
  loading.value = true;
  return customerApi.movingIntoMyCustomer({
    ids
  })
  .then(() => {
    ElMessage.success('已移入我的客户');
    return getList();
  })
  .finally(() => {
    loading.value = false;
  });
}

function handleMovingOutImportant(ids) {
  loading.value = true;
  return customerApi.movingOutImportant({
    ids,
    // followUpId: queryParams.followUp,
    // followUpName: queryParams.followUpName,
  })
  .then(() => {
    ElMessage.success('已移出重要客户');
    return getList();
  })
  .finally(() => {
    loading.value = false;
  });
}

function handleMovingIntoOpensea(ids) {
  loading.value = true;
  return customerApi.movingIntoOpensea({
    ids
  })
  .then(() => {
    ElMessage.success('已移入公海客户');
    return getList();
  })
  .finally(() => {
    loading.value = false;
  });
}
// ---  作用同跟进记录弹框右上 结束 ---

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, id?: number) => {
  formRef.value.open(type, id)
}

/** 公海客户 - 领取 */
function handleTake(ids) {
  if (loading.value) {
    return
  }

  loading.value = true
  return customerApi
    .take({
      ids
    })
    .then(() => {
      message.success('已领取')
      return getList()
    })
    .finally(() => {
      loading.value = false
    })
}

const assignDialogRef = ref()
function showAssignDialog(formState) {
  assignDialogRef.value.open(formState)
}
provide('showAssignDialog', showAssignDialog);

function handleAssign(payload) {
  if (!Boolean(payload.followUp.id)) {
    message.warning('请先选择分配人员')
    return
  }

  loading.value = true
  // 分配可选多人
  return customerApi
    .assign({
      customerType: payload.customerType,
      ids: payload.ids,
      followUpId: payload.followUp.id,
      followUpName: payload.followUp.nickname
    })
    .then(() => {
      message.success('已分配')
      getList()
      assignDialogRef.value.close()
      return
    })
    .finally(() => {
      loading.value = false
    })
}
provide('handleAssign', handleAssign);

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await customerApi.deletecustomer(id)
    message.success(t('common.delSuccess'))
    currentRow.value = {}
    // 刷新列表
    await getList()
  } catch {}
}

const checkedRows = ref<customer[]>([])
const checkedIds = computed<number[]>(() => checkedRows.value.map((item) => item.id))
const handleRowCheckboxChange = (records: customer[]) => {
  checkedRows.value = records
}

const followUpDialogRef = ref();
function handleRowClick(row, column) {
  if (column && 'selection' == column.type) {
    return;
  }
  followUpDialogRef.value.open(list.value.indexOf(row));
}

//分配客户，需要将选择的数据集合ids，和选择的用户id和用户nickname，组装为一个对象

/** 初始化 **/
onMounted(() => {
  getList();
  getFollowUpList();
})
</script>

<style scoped>
.customer-type-filter {
  background-color: #f5f7fa;
  padding: 6px 20px;
  border-radius: 10px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
}

.query-form {
  display: flex;
  flex-wrap: wrap;
  gap: 4px 12px;
  padding-bottom: 18px;
}

.query-form .el-button {
  height: 24px;
  padding: 4px 10px;
  font-size: 12px;
}

.query-form .el-form-item {
  margin: 0;
}

.query-form :deep(.el-form-item__content) {
  font-size: 12px;
}

.query-form :deep(.el-form-item__label),
.query-form :deep(.el-form-item__content) :where(.el-input, .el-select__wrapper, .el-range-input) {
  font-size: 12px;
}

.query-form :deep(.el-input__inner) {
  --el-input-inner-height: 22px;
}

.query-form :deep(.el-input__wrapper) {
  padding-left: 0;
  padding-right: 4px;
}

.query-form :deep(.el-date-editor .el-range-input) {
  width: 44%;
}

.query-form :deep(.el-date-editor.el-input__wrapper) {
  padding-right: 0;
}

.query-form :deep(.el-select__wrapper) {
  padding-left: 4px;
  padding-right: 6px;
  min-height: 24px;
  height: 22px;
  line-height: 22px;
}

.query-form :where(.el-date-editor.el-input, .el-date-editor.el-input__wrapper) {
  justify-content: left;
  padding-right: 0;
  --el-component-size: 24px;
}

.query-form :deep(.el-date-editor .el-range-separator) {
  flex: 0;
  width: 2px;
  padding-left: 2px;
  padding-right: 2px;
}

.filter-label {
  font-weight: 500;
  font-size: 14px;
}

.filter-btn {
  min-width: 80px;
  font-weight: 500;
}

:deep(.el-table--default) .cell {
  padding-left: 2px;
  padding-right: 2px;
}

.tag-group {
  display: flex;
  justify-content: center;
}

/* 这些说不定以后还用得上 */
.tag-group > .dict-tag { margin-right: -1px; }
.tag-group > .dict-tag:not(:first-child):not(:last-child) :deep(.el-tag) { border-radius: 0; }
.tag-group > .dict-tag:first-child:last-child:last-child :deep(.el-tag) { border-radius: 4px; }

.tag-group > .dict-tag:first-child :deep(.el-tag) {
  border-top-right-radius: 0;
  border-bottom-right-radius: 0;
}

.tag-group > .dict-tag:last-child :deep(.el-tag) {
  border-top-left-radius: 0;
  border-bottom-left-radius: 0;
}
</style>
